<template>
  <div>
    <el-card style="width: 70%;margin-left: 15%;text-align: center">
      <el-row>
        <span style="font-size: 300%;"> {{questionnaire.title}}</span>
      </el-row>
      <el-row>
        <span style="font-size: 150%;"> {{questionnaire.content}}</span>
      </el-row>
      <span style="font-size: 100%;"> 剩余答题次数:{{submit}} 截止时间:{{endTime}}</span>
      <el-divider></el-divider>
      <el-form :model="ruleForm" style="text-align: left" :rules="rules" ref="ruleForm">
        <vuedraggable v-model="ruleForm.topic" class="wrapper" @end="end">
          <div v-for="(item,index1) in ruleForm.topic"
               :key="index1">
              <span v-if="ruleForm.topic.length !== 0">
                <el-form-item>
                {{index1+1}}.{{item.title}}:
                </el-form-item>
              </span>

            <div class="show_radio" v-if="item.type === '单选'">
              <el-form-item prop="topic.${index1}.answer"   rules="{ required: true, message: '请选择答案', trigger: 'change' }" >
                <el-radio-group v-model="item.answer">
                  <el-radio v-for="(option, index2) in item.option" :label="option.value" @change="add">
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <div class="show_multiSelect" v-if="item.type === '多选'">
              <el-form-item prop="topic.${index1}.answer" rules="{ required: true, message: '请选择答案', trigger: 'change' }" >
                <el-checkbox-group v-model="item.answer" @change="add">
                  <el-checkbox v-for="(option, index2) in item.option" :label="option.value" >

                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>

            <div class="show_shortAnswer" v-if="item.type === '简答'">
              <el-form-item prop="topic.${index1}.answer"   rules="{ required: true, message: '请选择答案', trigger: 'change' }" >
                <el-input v-model="item.answer"
                          placeholder="请输入回答"
                          style="width: 20%"
                          clearable/>
              </el-form-item>
            </div>
          </div>
          <el-form-item style="margin-bottom: 0"><el-button @click = "submitClick()">提交</el-button></el-form-item>
        </vuedraggable>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import vuedraggable from 'vuedraggable'

export default {
  components: {
    vuedraggable
  },
  data(){
    return{
      exist:false,
      endTime:'',
      deadline:'',
      groupId:-1,
      submit:'',
      id:'',
      startTime:'',
      questionnaire:{
        id:'',
        userId:'',
        question:'',
        content:'',
        title:'',
        questionNumber:'',
        state:'',
        answerNumber:'',
      },
      ruleForm:{
        topic:[],
        allAnswer:[],
      },
      rules:{

      }
    }
  },
  methods:{
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //调用axios发送请求
          this.submitClick();

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitClick(){
      console.log(this.ruleForm.topic)
      let js = {answer: this.ruleForm.topic}
      if(this.exist){
        if(this.submit === 0){
          alert("剩余提交次数不足，无法继续提交")
        }else{
          this.$http({
            url:"http://47.104.100.60:81/updateAnswer",
            method:"post",
            data:{
              id: this.id,
              questionnaire_id: this.$route.query.questionnaireId,
              user_id: sessionStorage.getItem('userId'),
              answer: JSON.stringify(js),
              start_time: this.startTime,
              end_time: this.endTime,
              state: "完成",
              submit: this.submit
            }
          }).then(res =>{
            if(res.data !== null){
              if(res.data.fail == -1){
                alert("问卷已超时，无法继续提交")
              }else{
                alert("提交成功")
              }
            }
          }).catch(err=>{
            console.log(err)
          })
        }
      }else{
        this.$http({
          url:"http://47.104.100.60:81/insertAnswer",
          method:"post",
          data:{
            id: this.id,
            questionnaire_id: this.$route.query.questionnaireId,
            user_id: sessionStorage.getItem('userId'),
            answer: JSON.parse(js),
            start_time: this.startTime,
            end_time: this.endTime,
            state: "完成",
            submit: this.submit-1
          }
        }).then(res =>{
          if(res.data !== null){
            alert("提交成功")
          }
        }).catch(err=>{
          console.log(err)
        })
      }
      this.$router.push({
        path: '/'
      })
    }

  },
  mounted(){

    var date = new Date();
    var year = date.getFullYear(); //月份从0~11，所以加一
    var dateArr = [date.getMonth() + 1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()];
    for(var i=0;i<dateArr.length;i++){
      if (dateArr[i] >= 1 && dateArr[i] <= 9) {
        dateArr[i] = "0" + dateArr[i];
      }
    }
    this.startTime = year+'-'+dateArr[0]+'-'+dateArr[1]+' '+dateArr[2]+':'+dateArr[3]+':'+dateArr[4];
    this.$http({
      url:"http://47.104.100.60:81/getAnswerModel",
      method:"post",
      data:{
        questionnaire_id:this.$route.query.questionnaireId
      }
    }).then(res =>{
      // console.log(res.data)
      // console.log(res.data.question)
      this.endTime = res.data.end_time
      this.submit = res.data.submit

      this.$http({
        url:"http://47.104.100.60:83/findById",
        method:"post",
        data:{
          id:this.$route.query.questionnaireId
        }
      }).then(res =>{
        this.ruleForm.topic = JSON.parse(res.data.question).question
        this.questionnaire.content = res.data.content
        this.questionnaire.title = res.data.title
        this.questionnaire.id = this.$route.query.questionnaireId
        this.groupId = res.data.groupId
        console.log(this.groupId)
        if(this.groupId !== null){
          this.$http({
            url:" http://47.104.100.60:82/memberInGroup",
            method:"post",
            data:{
              memberId: sessionStorage.getItem('userId'),
              groupId: this.groupId
            }
          }).then(res =>{
            if(res.data == 0){
              alert("该问卷仅对特定群组开放")
              this.ruleForm.topic=[]
            }
          }).catch(err=>{
            console.log(err)
          })
        }

        this.$http({
          url:" http://47.104.100.60:81/getAnswerByQuestionIdAndUserId",
          method:"post",
          data:{
            questionnaire_id:this.$route.query.questionnaireId,
            user_id: sessionStorage.getItem('userId'),
          }
        }).then(res =>{
          if(res.data !== null){
            this.ruleForm.topic = JSON.parse(res.data.answer).answer
            this.submit = res.data.submit
            this.id = res.data.id
            this.endTime = res.data.end_time
            this.exist=true
          }
        }).catch(err=>{
          console.log(err)
        })

      }).catch(err=>{
        console.log(err)
      })
    }).catch(err=>{
      console.log(err)
    })

  }

}
</script>

<style scoped>

</style>

